package com.example.hotelback.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hotelback.entity.Params;
import com.example.hotelback.entity.Reservation;
import com.example.hotelback.entity.Room;
import com.example.hotelback.mapper.ReservationMapper;
import com.example.hotelback.mapper.RoomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;


@Service
public class ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private RoomMapper roomMapper;

    public List<Reservation> findAll() {
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete", 0);
        return reservationMapper.selectList(queryWrapper);
    }

    public IPage<Reservation> findByPage(Params params) {
        Page<Reservation> page = new Page<>(params.getCurrent(), params.getSize());
        IPage<Reservation> iPage = reservationMapper.selectAllReservationWithPagination(page);
        return iPage;
    }

    public List<Reservation> find(int id) {
        return reservationMapper.selectPersonalReservations(id);
    }

    /**
     * 删除订单要改变room总数
     * @param id
     */
    public void deleteReservation(int id) {
        Reservation reservation = reservationMapper.selectById(id);
        reservation.setIsDelete(1);
        reservationMapper.updateById(reservation);
        Room room = roomMapper.selectOneById(reservation.getRid());
        room.setReserveRoom(room.getReserveRoom() - 1); // 减少1
        if(room.getIsDelete() == 1) {
            room.setIsDelete(0);
        }
        roomMapper.updateById(room);
    }

    /**
     * 增加订单也要改变room总数
     * @param userId
     * @param roomId
     * @param params
     */
    public void addReservation(int userId, int roomId, Params params) {
        Reservation reservation = new Reservation();
        reservation.setUid(userId);
        reservation.setRid(roomId);
        reservation.setBookingTime(params.getBookingTime());
        reservation.setLeavingTime(params.getLeavingTime());
        reservation.setIsDelete(0);
        reservationMapper.insert(reservation);
        Room room = roomMapper.selectOneById(roomId);
        room.setReserveRoom(room.getReserveRoom() + 1); // 增加1
        roomMapper.updateById(room);
        if(Objects.equals(room.getReserveRoom(), room.getSumRoom())) {
            room.setIsDelete(1); // 隐藏
            roomMapper.updateById(room);
        }
    }
}
